/*
 * @Author: taoyuqing
 * @Date: 2023-03-21 01:23:38
 * @Description: 
 */
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:image_picker/image_picker.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:spree/widgets/common_container.dart';

import '../provider/model/user_model.dart';
import '../utils/utils.dart';

class ChangeUserInfo extends StatefulWidget {
  ChangeUserInfo({Key? key}) : super(key: key);

  @override
  State<ChangeUserInfo> createState() => _ChangeUserInfoState();
}

class _ChangeUserInfoState extends State<ChangeUserInfo> {
  TextEditingController _nickNameCtroller = TextEditingController();
  final ImagePicker picker = ImagePicker();
  late File _userImage; //存放获取到的本地路径
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text('change info'),
      ),
      body: Consumer<UserModel>(builder: (context, value, child) {
        return CommonContainer(
          padding: EdgeInsets.only(bottom: 20, left: 15, right: 15),
          child: Column(
            children: [
              Expanded(
                child: ListView(
                  padding: EdgeInsets.only(top: 20),
                  children: [
                    ListTile(
                      leading: Text(
                        'avatar:',
                        style: TextStyle(color: Colors.white, fontSize: 20),
                      ),
                      title: Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: [
                          Container(
                            width: 50,
                            height: 50,
                            child: value.avatar == ''
                                ? Image.asset(
                                    'images/avatar.jpg',
                                    fit: BoxFit.cover,
                                  )
                                : Image.network(
                                    '${value.avatar}',
                                    fit: BoxFit.cover,
                                  ),
                          ),
                        ],
                      ),
                      trailing: IconButton(
                          onPressed: () {
                            _showBasicModalBottomSheet(context, ontap: (type) {
                              print(type);
                              if (type == 1) {
                                _getCameraImage();
                              } else {
                                _getImage();
                              }
                            });
                          },
                          icon: Icon(
                            Icons.chevron_right_sharp,
                            color: Colors.white,
                            size: 26,
                          )),
                    ),
                    Divider(
                      color: Colors.white12,
                    ),
                    ListTile(
                      leading: Text(
                        'name:',
                        style: TextStyle(color: Colors.white, fontSize: 20),
                      ),
                      title: Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: [
                          Text(
                            value.nickname,
                            style:
                                TextStyle(color: Colors.white70, fontSize: 20),
                          ),
                        ],
                      ),
                      trailing: IconButton(
                          onPressed: () {
                            _showEdit();
                          },
                          icon: Icon(
                            Icons.chevron_right_sharp,
                            color: Colors.white,
                            size: 26,
                          )),
                    ),
                    Divider(
                      color: Colors.white12,
                    ),
                  ],
                ),
                flex: 1,
              ),
              GestureDetector(
                onTap: () {
                  Navigator.pushNamed(context, 'RestPassword');
                },
                child: Container(
                    margin: EdgeInsets.only(top: 12),
                    alignment: Alignment.center,
                    height: 50,
                    decoration: BoxDecoration(color: Color(0xFF7E68FF)),
                    child: Text(
                      'Update Password',
                      style: TextStyle(color: Colors.white),
                    )),
              ),
              GestureDetector(
                onTap: () {
                  _loginOut();
                },
                child: Container(
                    margin: EdgeInsets.only(top: 12),
                    alignment: Alignment.center,
                    height: 50,
                    decoration: BoxDecoration(color: Color(0xFF7E68FF)),
                    child: Text(
                      'Log Out',
                      style: TextStyle(color: Colors.white),
                    )),
              ),
            ],
          ),
        );
      }),
    );
  }

  _showEdit() {
    String nickName = Provider.of<UserModel>(context, listen: false).nickname;
    _nickNameCtroller.text = nickName;
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) {
        return AlertDialog(
          actions: [
            TextButton(
                onPressed: () {
                  Navigator.pop(context);
                },
                child: Text('取消')),
            TextButton(
                onPressed: () {
                  Provider.of<UserModel>(context, listen: false)
                      .setUserName(_nickNameCtroller.text);
                  Navigator.pop(context);
                },
                child: Text('确定'))
          ],
          title: Text("请输入新的昵称"),
          content: TextField(
            controller: _nickNameCtroller,
          ),
        );
      },
    );
  }

  _loginOut() async {
    // 清除本地信息
    final prefs = await SharedPreferences.getInstance();
    prefs.remove('accessToken');
    prefs.remove('userId');
    prefs.remove('userName');
    prefs.remove('passWord');
    Provider.of<UserModel>(context, listen: false).setUserInfo(
        name: '',
        id: '',
        mail: '',
        imgUrl: '',
        level: '',
        token: '',
        amount: '');
    EasyLoading.showSuccess(
      '退出登录',
    ).then((value) {
      Navigator.pop(context);
    });
  }

  _showBasicModalBottomSheet(context, {Function? ontap}) {
    showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return Container(
          height: 150,
          child: Column(
            children: [
              GestureDetector(
                onTap: () {
                  if (ontap != null) {
                    ontap(1);
                  }
                },
                child: Container(
                  alignment: Alignment.center,
                  color: Colors.white,
                  height: 60,
                  width: Utils().getScreenWidth(context),
                  child: Text('拍照'),
                ),
              ),
              Divider(
                color: Colors.black54,
              ),
              GestureDetector(
                onTap: () {
                  if (ontap != null) {
                    ontap(2);
                  }
                },
                child: Container(
                  alignment: Alignment.center,
                  color: Colors.white,
                  height: 60,
                  width: Utils().getScreenWidth(context),
                  child: Text('相册中选择'),
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  Future _getCameraImage() async {
    final cameraImages = await picker.pickImage(source: ImageSource.camera);
    if (mounted) {
      setState(() {
        //拍摄照片不为空
        if (cameraImages != null) {
          _userImage = File(cameraImages.path);
          print('你选择的路径是：${_userImage.toString()}');
          //图片为空
        } else {
          print('没有照片可以选择');
        }
      });
    }
  }

  Future _getImage() async {
    //选择相册
    final pickerImages = await picker.pickImage(source: ImageSource.gallery);
    if (mounted) {
      setState(() {
        if (pickerImages != null) {
          _userImage = File(pickerImages.path);
          print('路径是：${_userImage.toString()}');
        } else {
          print('没有照片可以选择');
        }
      });
    }
  }
}
